import csv

from django.core.management.base import BaseCommand
from django.core.files.uploadedfile import InMemoryUploadedFile

from oscar.apps.catalogue.models import Product

class Command(BaseCommand):

    def handle(self, *args, **options):
        # Start processing CSV
        if isinstance(args[0], InMemoryUploadedFile):
            csv_reader = csv.reader(args[0], delimiter=',')
        else:
            f = open(args[0], 'rb')
            csv_reader = csv.reader(f, delimiter=',')

        for row in csv_reader:
            if not row: continue

            sku = row[0]
            stock = row[1]

            print sku
            p_var = Product.objects.filter(upc=sku)
            if not p_var.exists():
                print 'Product with SKU %s does not exist' % sku
                continue
            p_var = p_var[0]

            rec = p_var.stockrecord
            rec.num_in_stock = int(stock)
            rec.save()
